package com.wmh.baseservice.common.utils;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;


@Configuration
public class CosUtil {

    @Value("${tencent.SecretId}")
    private String secretId;
    @Value("${tencent.SecretKey}")
    private String secretKey;
    @Value("${tencent.cos.region}")
    private String region;
    @Value("${tencent.cos.bucketName}")
    private String bucketName;
    @Value("${tencent.cos.url}")
    private String path;
    @Value("${tencent.cos.open}")
    private boolean openCos;


    public static String staticSecretId;
    public static String staticSecretKey;
    public static String staticRegion;
    public static String staticBucketName;
    public static String staticPath;
    public static boolean staticOpenCos;

    @PostConstruct
    private void getStatic() {
        staticSecretId = secretId;
        staticBucketName = bucketName;
        staticPath = path;
        staticSecretKey = secretKey;
        staticRegion = region;
        staticOpenCos = openCos;
    }


    /**
     * 上传文件到cos
     * @param path 当前图片文件路径
     * @param uploadPath 上传到cos的文件路径
     * @param fileName 文件名称
     * @return 返回图片名称
     */
    public static String upload(String path, String uploadPath, String fileName) {
        COSClient cosClient = cosClient(staticSecretId, staticSecretKey, staticRegion);
        // 指定要上传的文件
        File localFile = new File(path+"/"+fileName);
        localFile.setWritable(true, false);
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        PutObjectRequest putObjectRequest = new PutObjectRequest(staticBucketName, uploadPath+"/"+fileName, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        return fileName;

    }

    public static COSClient cosClient(String secretId, String secretKey, String regionName) {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

}
